#include "HD447807Bits.h"
#include "HD44780AnalyzerSettings.h"

HD447807Bits::HD447807Bits(void)
{
}

HD447807Bits::~HD447807Bits(void)
{
}

void HD447807Bits::CheckBusyFlagAsLoop()
{
    CheckBusyFlagAsPulse();
}

void HD447807Bits::CheckBusyFlagAsPulse()
{
    for ( int i = 0; i < 2; ++i )
    {
        SetControlForBusyFlag();
        WaitInNanos( TIME_AS );

        (*mData)[ mSettings->GetRe()]->TransitionIfNeeded( BIT_HIGH );
        WaitInNanos( TIME_DDR );

        SetDataLines( i == 0 ? 0x80 : 0x00 );
        WaitInMicros(5);

        SetControlLow();
        SetDataLines(0);
        WaitInNanos(200);

        SetControlForBusyFlag();
        WaitInNanos( TIME_AS );

        (*mData)[ mSettings->GetRe()]->TransitionIfNeeded( BIT_HIGH );
        WaitInNanos( TIME_DDR );

        SetDataLines(  0x00 );
        WaitInMicros(5);

        SetControlLow();
        SetDataLines(0);
        WaitInNanos(200);
    }
}

void HD447807Bits::SendData( U8 Data )
{
    for ( int i = 0; i < 2; ++i)
    {
        SetControlForData();
        SetDataLines(Data);
        WaitInNanos( TIME_AS );
        PulseEnableLine();
        SetControlLow();
        SetDataLines(0);
        WaitInNanos( TIME_YCE - (TIME_AS + TIME_PWEH + TIME_ER + TIME_H) ); 
        Data = Data << 4;
    }
    CheckBusyFlagAsPulse();
}

void  HD447807Bits::SendCommand( U8 Command )
{
    int Limit = (Command & IHD44780::CMD_FUNCTION) == IHD44780::CMD_FUNCTION ? 1 : 2;
    for ( int i = 0; i < Limit; ++i)
    {
        SetControlForCommand();
        SetDataLines(Command);
        WaitInNanos( TIME_AS );
        PulseEnableLine();
        SetControlLow();
        SetDataLines(0);
        WaitInNanos( TIME_YCE - (TIME_AS + TIME_PWEH + TIME_ER + TIME_H) ); 
        Command = Command << 4;
    }
}

void HD447807Bits::SetDataLines( U8 Data )
{
    (*mData)[ mSettings->GetData4() ]->TransitionIfNeeded( Data & 0x10 ? BIT_HIGH : BIT_LOW  );
    (*mData)[ mSettings->GetData5() ]->TransitionIfNeeded( Data & 0X20 ? BIT_HIGH : BIT_LOW  );
    (*mData)[ mSettings->GetData6() ]->TransitionIfNeeded( Data & 0X40 ? BIT_HIGH : BIT_LOW  );
    (*mData)[ mSettings->GetData7() ]->TransitionIfNeeded( Data & 0X80 ? BIT_HIGH : BIT_LOW  );
}


